package com.patterns.demo.prototype;

import java.io.*;

/**
 * Author: SamGroves
 * <p>
 * Description: 原型的深浅复制方法
 * <p>
 * Date: 2017/11/29
 */
public class Prototype implements Cloneable, Serializable {


    /**
     * 浅复制
     */
    public Object lightClone() throws CloneNotSupportedException{

        Prototype prototype = null;

        try {

            prototype = (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {

            e.printStackTrace();
        }
        return prototype;
    }

    /**
     * 深复制
     */
    public Object deepClone() throws IOException, ClassNotFoundException{

         /* 写入当前对象的二进制流 */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);
        oos.flush();
        oos.close();

        /* 读出二进制流产生的新对象 */
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        ois.close();
        return ois.readObject();
    }
}